package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmLoginDto;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.AppJwtUtil;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {


    @Override
    public ResponseResult login(WmLoginDto dto) {

        if(StringUtils.isNotBlank(dto.getName())&& StringUtils.isNotBlank(dto.getPassword())){
            WmUser wmUser = getOne(Wrappers.<WmUser>lambdaQuery().eq(WmUser::getName, dto.getName()));
            if (wmUser!=null){
                String salt = wmUser.getSalt();
                String password = dto.getPassword();
                String pwd = DigestUtils.md5DigestAsHex((password + salt).getBytes(StandardCharsets.UTF_8));
                if (wmUser.getPassword().equals(pwd)){
                    String token = AppJwtUtil.getToken(wmUser.getId().longValue());
                    Map<String, Object> map = new HashMap<>();
                    wmUser.setSalt("");
                    wmUser.setPassword("");
                    map.put("user",wmUser);
                    map.put("token",token);

                    return ResponseResult.okResult(map);
                }
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);

            }else {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
            }
        }return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);



    }
}